"""
# coding     : utf-8 
# Time       : 2025/6/10 16:11
# Author     : chenxianb
# version    : python 3.8.2
# Description: 获取红牛官网中的中国分公司
"""
import os.path
import time

import openpyxl
import requests
from bs4 import BeautifulSoup


def get_html_text(url):
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0"}
    try:
        r = requests.get(url, headers=header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""


def get_company(html):
    """获取分公司信息"""
    company = []
    addr = []
    tel = []
    mail = []
    lat = []  # 纬度
    long = []  # 精度
    info = []

    soup = BeautifulSoup(html, "html.parser")
    txt = soup.find(class_="con")
    for item in txt.find_all("li"):
        # 地址
        # address = item["data-describe"]
        # 公司名
        # company = item["data-title"]

        # 纬度
        latitude = item["data-latitude"]
        lat.append(latitude)
        # 精度
        longitude = item["data-longitude"]
        long.append(longitude)

    # 公司
    names = soup.find_all("h2")
    for name in names:
        company.append(name.text)
    # 地址
    address = soup.find_all("p", "mapIco")
    for a in address:
        addr.append(a.text)

    # 邮编
    mails = soup.find_all(class_="mailIco")
    for m in mails:
        mail.append(m.text)

    # 电话
    tels = soup.find_all(class_="telIco")
    for t in tels:
        tel.append(t.text)

    # 把相关信息组装成一条完整记录
    for i in range(len(company)):
        info.append([company[i], addr[i], mail[i], tel[i], long[i], lat[i]])
    return info


def write_to_excel(info, file):
    """存入Excel中"""
    if not os.path.exists(file):
        os.mkdir(file)

    timestamp = int(time.time())
    filepath = f"{file}/红牛中国分公司信息{timestamp}.xlsx"

    wb = openpyxl.Workbook(filepath)
    table = wb.create_sheet("分公司", 0)
    title = ["公司名称", "地址", "邮编", "联系电话", "经度", "纬度"]
    table.append(title)
    for item in info:
        table.append(item)

    wb.save(filepath)
    print(f" 红牛中国分公司信息{timestamp}.xlsx 保存成功")


if __name__ == '__main__':
    url = "http://www.redbull.com.cn/about/branch"
    path = "./分公司/"
    html = get_html_text(url)
    result = get_company(html)
    write_to_excel(result,path)
